﻿using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XB.Core.DAO.Audit;

namespace MemoryStore.Core.DAO.Audit
{
    public class PropertyChangeInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            if (!invocation.Method.Name.StartsWith("set_")
                || invocation.Arguments == null || invocation.Arguments.Length == 0
                || !(invocation.Proxy is IAudit))
            {
                invocation.Proceed();
                return;
            }

            var propertyName = invocation.Method.Name.Substring(4);
            var targetPropertyInfo = invocation.TargetType.GetProperty(propertyName);
            if (targetPropertyInfo == null)
            {
                invocation.Proceed();
                return;
            }

            var oldValue = targetPropertyInfo.GetValue(invocation.InvocationTarget);

            invocation.Proceed();

            if (oldValue.ToString() != invocation.Arguments[0].ToString())
            {
                var auditProxy = (IAudit)invocation.Proxy;
                if (auditProxy.GetAuditHandler() != null)
                {
                    auditProxy.GetAuditHandler().Modify(propertyName, oldValue.ToString(), invocation.Arguments[0].ToString());
                }
            }
        }
    }
}
